//
//  UIViewUtil.swift
//  UserApp_iOS
//
//  Created by linlin on 2019/9/10.
//  Copyright © 2019 linlin. All rights reserved.
//

import Foundation
import UIKit
import Kingfisher
let colorGray = UIColor(red: 158/255, green: 158/255, blue: 158/255, alpha: 1)
let colorEndGraduate = UIColor(red: 255/255, green: 147/255, blue: 101/255, alpha: 1)
@IBDesignable
extension UIView{
    @objc var width: CGFloat {
        get{
            return frame.width
        }
        
        set{
            let f: CGRect = CGRect(x: frame.origin.x, y: frame.origin.y, width: newValue, height: frame.height)
            frame = f
        }
    }
    
    @objc var height: CGFloat {
        get{
            return frame.height
        }
        
        set{
            let f: CGRect = CGRect(x: frame.origin.x, y: frame.origin.y, width: frame.width, height: newValue)
            frame = f
        }
    }
    
    @objc var left: CGFloat {
        get{
            return frame.origin.x
        }
        
        set{
            let f: CGRect = CGRect(x: newValue, y: frame.origin.y, width: frame.width, height: frame.height)
            frame = f
        }
    }
    
    @objc var right: CGFloat {
        get{
            return frame.origin.x + frame.width
        }
        set{
            let f: CGRect = CGRect(x: newValue - frame.width, y: frame.origin.y, width: frame.width, height: frame.height)
            frame = f
        }
    }

    var top: CGFloat {
        get{
            return frame.origin.y
        }
        
        set{
            let f: CGRect = CGRect(x: frame.origin.x, y: newValue, width: frame.width, height: frame.height)
            frame = f
        }
    }
    
    var bottom: CGFloat {
        get{
            return frame.origin.y + frame.height
        }
        set{
            let f: CGRect = CGRect(x: frame.origin.x, y: newValue - frame.height, width: frame.width, height: frame.height)
            frame = f
        }
    }
    
    @IBInspectable var borderWidth : CGFloat {
        set{
            layer.borderWidth = newValue
        }
        get{
            return layer.borderWidth
        }
    }
    
    @IBInspectable var borderColor : UIColor? {
        set{
            layer.borderColor = newValue?.cgColor
        }
        get{
            if let color = layer.borderColor {
                return UIColor(cgColor: color)
            }
            return nil
        }
    }
    
    @IBInspectable var cornerRadius : CGFloat {
        set{
            layer.cornerRadius = newValue
        }
        get{
            return layer.cornerRadius
        }
    }
    
    @IBInspectable var masksToBounds : Bool{
        set{
            layer.masksToBounds = newValue
        }
        get{
            return layer.masksToBounds
        }
    }
    
    var firstResponder: UIView? {
        var next: UIView?
        subviews.forEach { (sub) in
            if sub.isFirstResponder {
                next = sub
            }
        }
        return next
    }
    
    var nextStep: UIView? {
        var next: UIView?
        
        if let first = firstResponder {
            return first
        } else {
            for sub in subviews {
                next = sub.nextStep
                if let _ = next {
                    return next
                }
            }
        }
        
        return next
    }
    
    var topTableView: UITableView?{
        get{
            var nextResponder: UIResponder? = next
            while let nextResponds = nextResponder {
                if nextResponds.isKind(of: UITableView.classForCoder()){
                    return nextResponds as? UITableView
                }
                nextResponder = nextResponder?.next
            }
            
            return nil
        }
    }
    
    var topViewController: UIViewController?{
        get{
            var nextResponder: UIResponder? = next
            while let nextResponds = nextResponder {
                if nextResponds.isKind(of: UIViewController.classForCoder()){
                    return nextResponds as? UIViewController
                }
                nextResponder = nextResponder?.next
            }
            
            return nil
        }
    }
    
    var topNavigationViewController: UINavigationController?{
        get{
            var nextResponder: UIResponder? = next
            while let nextResponds = nextResponder {
                if nextResponds.isKind(of: UINavigationController.classForCoder()){
                    return nextResponds as? UINavigationController
                }
                nextResponder = nextResponder?.next
            }
            
            return nil
        }
    }
    
    var topTabBarViewController: UITabBarController?{
        get{
            var nextResponder: UIResponder? = next
            while let nextResponds = nextResponder {
                if nextResponds.isKind(of: UITabBarController.classForCoder()){
                    return nextResponds as? UITabBarController
                }
                nextResponder = nextResponder?.next
            }
            
            return nil
        }
    }
    
    func setGraduateBackground(startColor: UIColor, endColor: UIColor) -> Void {
        let graduateLayer: CAGradientLayer = CAGradientLayer()
        graduateLayer.frame = bounds
        graduateLayer.colors = [colorTheme.cgColor, colorEndGraduate.cgColor]
        graduateLayer.type = .axial
        graduateLayer.locations = [0, 1]
        graduateLayer.startPoint = CGPoint(x: 0, y: 0)
        graduateLayer.endPoint = CGPoint(x: 0, y: 1)
        layer.insertSublayer(graduateLayer, below: mask?.layer)
    }
    
    func updateConstraitHeight(height: CGFloat) -> Void {
        self.constraints.forEach { (constraint) in
            if constraint.firstAttribute == .height{
                constraint.constant = height
                return
            }
        }
    }
    
    func updateConstraitWidth(width: CGFloat) -> Void {
        self.constraints.forEach { (constraint) in
            if constraint.firstAttribute == .width{
                constraint.constant = width
                return
            }
        }
    }
}

extension UIImageView{
    func setImage(with url: String?, placeHolder: String? = nil) -> Void {
        if let imageurl = url {
            if imageurl.count > 0 {
                self.kf.setImage(with: ImageResource(downloadURL: URL(string: imageurl)!), placeholder: UIImage(named: placeHolder ?? "default_img"))
            }
        }
    }
}

extension UIButton{
    func setImage(with url: String?) -> Void {
        if let imageurl = url {
            if imageurl.count > 0 {
                self.kf.setImage(with: ImageResource(downloadURL: URL(string: imageurl)!), for: .normal, placeholder: UIImage(named: "default_img"))
            }
        }
    }
    
    func setBackgroundImg(with url: String?) -> Void {
        if let imageurl = url {
            if imageurl.count > 0 {
                self.kf.setBackgroundImage(with: ImageResource(downloadURL: URL(string: imageurl)!), for: .normal, placeholder: UIImage(named: "default_img"))
            }
        }
    }
}

extension UILabel{
    static func getSizeToFit(with: String, attributes: [NSAttributedString.Key : Any]?,width: CGFloat=CGFloat(MAXFLOAT), height: CGFloat=CGFloat(MAXFLOAT)) -> CGSize {
        let size = (with as NSString).boundingRect(with: CGSize(width: width, height: height), options: [.truncatesLastVisibleLine, .usesLineFragmentOrigin], attributes: attributes, context: nil).size
        return size
    }
    
    func setBackgroundImage(image: UIImage) {
        let backgroundImg = image.scaleWithSize(size: CGSize(width: self.width, height: self.height))
        self.backgroundColor = UIColor(patternImage: backgroundImg)
    }
}

extension UITextField{
//    open override func draw(_ rect: CGRect) {
//        let insets = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
//        super.draw(rect.inset(by: insets))
//    }
//
//    open override var intrinsicContentSize: CGSize {
//        let size = super.intrinsicContentSize
//        return CGSize(width: size.width + 10 + 10,
//                      height: size.height)
//    }
}

extension CGSize {
    mutating func setWidth(_ width:CGFloat) -> Void{
        self = CGSize(width: width, height: self.height)
    }
    
    mutating func setHeight(_ height:CGFloat) -> Void{
        self = CGSize(width: self.width, height: height)
    }
}

extension UIImage{
    //maxsize图片最大内存，单位kb
    func compressImage(maxSize: Int) -> UIImage {
        var storage: Int = self.jpegData(compressionQuality: 1)?.count ?? 0
        
        var resultImage: UIImage = self
        var isLimited: Bool = false
        while storage > maxSize*1024 {
            if resultImage.size.width > self.size.width/2 || isLimited {
                let size = CGSize(width: resultImage.size.width/10*9, height: resultImage.size.height/10*9)
                resultImage = resultImage.scaleWithSize(size: size)
            }
            let tempImgData = resultImage.jpegData(compressionQuality: 0.8)!
            isLimited = tempImgData.count >= storage
            resultImage = UIImage(data: tempImgData)!
            storage = tempImgData.count
        }
        
        return resultImage
    }

    func scaleWithSize(size: CGSize) -> UIImage {
        var resultImage: UIImage = self
        UIGraphicsBeginImageContext(size)
        resultImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
        resultImage = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
        UIGraphicsEndImageContext()
        return resultImage
    }
}

extension UIScrollView {
    var listEmptyView: UIView {
        guard let emptyView = viewWithTag(100000) else {
            let emptyView = UIView(frame: CGRect(x: 0, y: 0, width: self.width, height: self.height))
            let img = UIImage(named: "orderlist_null")
            let imgView = UIImageView(image: img)
            let imgW = img?.size.width ?? 0.0
            let imgH = img?.size.height ?? 0.0
            imgView.frame = CGRect(x: (emptyView.width - imgW) / 2.0, y: (emptyView.height - imgH) / 2.0-100, width:imgW, height: imgH)
            emptyView.addSubview(imgView)
            let label = UILabel(frame: CGRect(x: 0, y: imgView.bottom+10, width: emptyView.width, height: 30))
            label.text = "目前暂时没有相关数据"
            label.textAlignment = .center
            label.font = UIFont.systemFont(ofSize: 16)
            label.textColor = colorGray
            emptyView.addSubview(label)
            emptyView.tag = 100000
            return emptyView
        }
    
        return emptyView
    }
    
    func addKeyboardObserver() {
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    @objc func keyboardWillShow(notification: Notification) {
        let keyboardHeight = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
        if let first = self.nextStep {
            let rect = first.convert(first.frame, to: self.topViewController?.view)
            let bottom = rect.size.height + rect.origin.y
            let offsetY: CGFloat = bottom + keyboardHeight - (self.topViewController?.view.height ?? 0) 
            if offsetY > 0 {
                self.contentOffset.y = offsetY + self.contentOffset.y
            }
        }
    }
    
    @objc func keyboardWillHide(notification: Notification) {
        let keyboardHeight = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue.height
        
    }
    
    func removeKeyboardObserver() {
//        NotificationUtil.removeObserver(observer: self)
    }
}

extension UITableView {
    func setEmptyFooterView() {
        self.tableFooterView = UIView(frame: CGRect.zero)
    }
    
    func notifyDataChanged() {
        setNeedsLayout()
        reloadData()
        
        if self.numberOfSections == 0 || (self.numberOfSections == 1 && self.numberOfRows(inSection: 0) == 0) {
            tableFooterView = listEmptyView
        } else {
            setEmptyFooterView()
        }
    }
}
